import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('../views/layout/LayoutPage.vue'),
      redirect: '/article/manage',
      // children 下的子路由指向的视图,都是在 LayoutPage 下的router-view 中渲染,是作为 LayoutPage 的二级路由
      children: [
        {
          path: '/article/channel',
          name: 'ArticleChannel',
          component: () => import('../views/article/ArticleChannel.vue'),
        },
        {
          path: '/article/manage',
          name: 'ArticleManage',
          component: () => import('../views/article/ArticleManage.vue'),
        },
        {
          path: '/user/avatar',
          name: 'userAvatar',
          component: () => import('../views/user/UserAvatar.vue'),
        },
        {
          path: '/user/profile',
          name: 'UserProfile',
          component: () => import('../views/user/UserProfile.vue'),
        },
        {
          path: '/user/password',
          name: 'UserPassword',
          component: () => import('../views/user/UserPassword.vue'),
        },
      ],
    },
    {
      path: '/login',
      name: 'LoginPage',
      component: () => import('../views/login/LoginPage.vue'),
    },
  ],
})

// 登录访问拦截
router.beforeEach((to) => {
  const userStore = useUserStore()
  if (!userStore.token && to.path !== '/login') return '/login'
})

export default router
